package com.moss.common.util;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.moss.common.domain.LoginUser;
import com.moss.common.jwt.JwtUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class TokenUtil {


    public static String getToken(LoginUser loginUser){
        Map<String,String> map = new HashMap<>();
        map.put("userId",String.valueOf(loginUser.getUserId()));
        map.put("realName",loginUser.getRealName());
        map.put("orgId",String.valueOf(loginUser.getOrgId()));
        return JwtUtil.generateToken(map);
    }

    public static String getUserId(String token){
        DecodedJWT tokenInfo = JwtUtil.getTokenInfo(token);
        return tokenInfo.getClaim("userId").asString();
    }

    public static String getCompanyId(String token){
        DecodedJWT tokenInfo = JwtUtil.getTokenInfo(token);
        return tokenInfo.getClaim("companyId").asString();
    }

    public static LoginUser getLoginUser(String token){
        DecodedJWT tokenInfo = JwtUtil.getTokenInfo(token);
        return new LoginUser(tokenInfo);
    }

    public static boolean isAdmin(String userId, String adminKey) {
        return StringUtils.isNotEmpty(userId) && adminKey.equals(userId);
    }

    public static String getOrgId(String token) {
        DecodedJWT tokenInfo = JwtUtil.getTokenInfo(token);
        return tokenInfo.getClaim("orgId").asString();
    }
}
